layui.use(['form', 'laytpl', 'layer', 'jquery'], function () {
    var laytpl = layui.laytpl,
        $ = layui.$,
        form = layui.form,
        layer = layui.layer;

    var schools = {};
    var subCampusList = {};

    function getSchools() {
        $.ajax({
            url: 'schools.json',
            async: false,
            dataType: "json",
            success: function (data) {
                schools = data;
            }
        });
    }

    $(document).ready(function () {
        checkToken();
    });

    Date.prototype.Format = function (format) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "H+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return format;
    };

    form.on('submit(login)', function (data) {
        console.log(data.field);
        layer.load(1);
        $.ajax({
            type: "POST"
            , url: '/api/session/new'
            , contentType: 'application/x-www-form-urlencoded;charset=UTF-8'
            , dataType: "json"
            , cache: false
            , data: data.field
            ,timeout:6000
            , success: function (ret) {
                console.log(ret);
                if (ret.code === 0) {
                    layer.closeAll('loading');
                    layer.msg("登陆成功");
                    saveUserPublicInfo(ret);
                    goIndex();
                }

                if (ret.code === 6) {
                    layer.msg(ret.msg);
                    layer.msg("登录失败");
                }
                if (ret.code === -1) {
                    layer.msg(ret.msg);
                    layer.msg("登录失败");
                }
                layer.closeAll('loading');
            }
            ,error:function(){
                layer.msg('服务器正在休息~待会再来~');
                setTimeout(function () {
                    layer.closeAll('loading');
                },1000);
            }
        });
        return false;
    });

    $('#registerLink').on('click', function () {
        layer.open({
            title: false
            , type: 1
            , area: ['400px']
            , content: $('#register_form').html()
            , success: function (layero, index) {
                getSchools();
                renderSelectSchool();
                form.render('select');
                form.render('radio');

                form.on('select(school-filter)', function (data) {
                    getSubCampusList(data.value);
                    renderSelectSubCampus();
                    form.render();
                });

                form.on('submit(register)', function (data) {
                    data.field.timeCreate = new Date().Format("yyyy-MM-dd HH:mm:ss");
                    layer.load(1);
                    $.ajax({
                        type: "POST"
                        , url: '/api/users/new'
                        , contentType: 'application/json;charset=UTF-8'
                        , dataType: "json"
                        , cache: false
                        , timeout: 10000
                        , data: JSON.stringify(data.field)
                        , success: function (ret) {
                            console.log(ret);
                            layer.closeAll('loading');
                            if (ret.code === -1) {
                                layer.msg("位置错误");
                            }
                            if (ret.code === 4) {
                                layer.msg(ret.msg + "\n" + ret.data);
                            }
                            if (ret.code === 7) {
                                layer.msg("用户名已存在");
                            }
                            if (ret.code === 0) {
                                layer.msg("注册成功");
                                $("#LAY-user-login-username").val(data.field.nickname);
                                $("#LAY-user-login-password").val(data.field.password);
                                setTimeout(function () {
                                    layer.closeAll();
                                }, 1000);
                            }
                        }
                        , error: function () {
                            layer.msg("注册失败");
                            setTimeout(function () {
                                layer.closeAll('loading');
                            }, 1000)
                        }
                    });
                    return false;
                })
            }
        });
    });


    //注册表单中 选择学校 下拉框渲染
    function renderSelectSchool() {
        var getTpl = selectSchoolTpl.innerHTML,
            view = document.getElementById('selSchool');
        laytpl(getTpl).render(schools, function (html) {
            view.innerHTML = html;
        });
    }

    //注册表单中 选择校区 下拉框渲染
    function renderSelectSubCampus() {
        var getTpl = selectSubCampusTpl.innerHTML,
            view = document.getElementById('selSubCampus');
        console.log(subCampusList);
        laytpl(getTpl).render(subCampusList, function (html) {
            view.innerHTML = html;
        });
    }

    function getSubCampusList(schoolName) {
        var schoolList = schools.list;
        for (var i in schoolList) {
            if (schoolList[i].name === schoolName) {
                subCampusList.list = schoolList[i].subCampus;
                return;
            }
        }
    }

    //跳转登陆
    function goIndex() {
        location.href = '/html/index.html';
    }

    //检查是否登陆
    function checkToken() {
        if (localStorage.getItem("userId") != null) {
            console.log("存在userID 验证token是否有效");
           $.ajax({
               type: "POST"
               , url: "/api/session/valid"
               ,timeout: 6000
               , success:function (ret) {
                   if (ret.code === 0){
                       console.log("still valid!")
                       goIndex();
                   }
               }
               ,error:function () {
                   layer.msg("请保持网络良好~");
               }
           })
        }
    }

    function saveUserPublicInfo(ret) {
        localStorage.setItem("prefix", ret.data.prefix);
        localStorage.setItem("userId", ret.data.userId);
        localStorage.setItem("nickname", ret.data.nickname);
        localStorage.setItem("headerImg", ret.data.headImg);
    }
});